package com.lzb.findphone.activity;

import android.media.AudioManager;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.SeekBar;

import androidx.activity.EdgeToEdge;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.graphics.Insets;
import androidx.core.view.ViewCompat;
import androidx.core.view.WindowInsetsCompat;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.LinearLayoutManager;

import com.blankj.utilcode.util.AppUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.blankj.utilcode.util.UriUtils;
import com.blankj.utilcode.util.VolumeUtils;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.listener.OnItemClickListener;
import com.lzb.findphone.BaseAc;
import com.lzb.findphone.HomeActivity;
import com.lzb.findphone.R;
import com.lzb.findphone.adapter.DurationAdapter;
import com.lzb.findphone.adapter.SoundAdapter;
import com.lzb.findphone.basic.media.AudioPlayerImpl;
import com.lzb.findphone.basic.media.IAudioPlayer;
import com.lzb.findphone.bean.DurationBean;
import com.lzb.findphone.bean.SettingBean;
import com.lzb.findphone.bean.SoundBean;
import com.lzb.findphone.databinding.ActivitySoundBinding;
import com.lzb.findphone.dialog.RingtoneChangeDialog;
import com.lzb.findphone.utils.AppSpUtils;

import java.util.ArrayList;
import java.util.List;

public class SoundActivity extends BaseAc<ActivitySoundBinding> implements View.OnClickListener, OnItemClickListener {

    public static int soundPos;
    private SoundAdapter soundAdapter;
    private DurationAdapter durationAdapter;
    private int durationPos;
    private IAudioPlayer mAudioPlayer;
    private SettingBean settingBean;
    private long duration;
    private boolean isFlashlight, isVibration;
    private int max, min, now, progress;


    @Override
    protected int onCreate() {
        return R.layout.activity_sound;
    }

    @Override
    protected void initView() {
        mDataBinding.ivSoundBack.setOnClickListener(view -> getOnBackPressedDispatcher().onBackPressed());

        mDataBinding.llSetRingtone.setOnClickListener(this);
        mDataBinding.llPlay.setOnClickListener(this);
        mDataBinding.ivMin.setOnClickListener(this);
        mDataBinding.ivAdd.setOnClickListener(this);
        mDataBinding.ivFlashlightMode.setOnClickListener(this);
        mDataBinding.ivVibrationMode.setOnClickListener(this);
        mDataBinding.tvApply.setOnClickListener(this);

        mAudioPlayer = new AudioPlayerImpl();
        mAudioPlayer.setListener(new IAudioPlayer.IListener() {
            @Override
            public void onUpdatePlayTime(int curPlayTime, int duration) {

            }

            @Override
            public void onPlayChange(boolean isPlaying) {
                if (isPlaying) {
                    mDataBinding.ivPlay.setImageResource(R.drawable.icon_stop);
                    mDataBinding.tvPlay.setText(getString(R.string.stop_trial_listening));
                } else {
                    mDataBinding.ivPlay.setImageResource(R.drawable.icon_play);
                    mDataBinding.tvPlay.setText(getString(R.string.start_trial_listening));
                }
            }
        });

        max = VolumeUtils.getMaxVolume(AudioManager.STREAM_MUSIC);
        min = VolumeUtils.getMinVolume(AudioManager.STREAM_MUSIC);
        now = VolumeUtils.getVolume(AudioManager.STREAM_MUSIC);
        progress = now * 100 / (max - min);
        mDataBinding.tvProgress.setText(progress + getString(R.string.unit_percent));
        mDataBinding.sbProgress.setProgress(progress);
        mDataBinding.sbProgress.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            @Override
            public void onProgressChanged(SeekBar seekBar, int i, boolean b) {
                progress = i;
                setVolume();
            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {

            }

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {

            }
        });

        mDataBinding.rvSoundList.setLayoutManager(new LinearLayoutManager(mContext, LinearLayoutManager.HORIZONTAL, false));
        soundAdapter = new SoundAdapter();
        mDataBinding.rvSoundList.setAdapter(soundAdapter);
        soundAdapter.setOnItemClickListener(this);

        mDataBinding.rvDurationList.setLayoutManager(new GridLayoutManager(mContext, 4));
        durationAdapter = new DurationAdapter();
        mDataBinding.rvDurationList.setAdapter(durationAdapter);
        durationAdapter.setOnItemClickListener(this);
    }

    @Override
    public void onClick(View view) {
        int id = view.getId();
        if (id == R.id.llSetRingtone) {//设为铃声
            showRingtoneChangeDialog(settingBean.getRing());
        } else if (id == R.id.llPlay) {//播放/暂停
            if (mAudioPlayer.isPlaying()) {
                mAudioPlayer.pause();
            } else {
                Uri uri = Uri.parse("android.resource://" + AppUtils.getAppPackageName() + "/" + soundAdapter.getItem(soundPos).getRawId());
                mAudioPlayer.play(UriUtils.uri2File(uri).getPath());
            }
        } else if (id == R.id.ivMin) {//音量-
            if (progress == 0) return;
            progress--;
            setVolume();
        } else if (id == R.id.ivAdd) {//音量+
            if (progress == 100) return;
            progress++;
            setVolume();
        } else if (id == R.id.ivFlashlightMode) {//闪光模式
            isFlashlight = !isFlashlight;
            mDataBinding.ivFlashlightMode.setImageResource(isFlashlight ? R.drawable.akai : R.drawable.aguan);
        } else if (id == R.id.ivVibrationMode) {//震动模式
            isVibration = !isVibration;
            mDataBinding.ivVibrationMode.setImageResource(isVibration ? R.drawable.akai : R.drawable.aguan);
        } else if (id == R.id.tvApply) {//应用
            apply();
        }
    }

    @Override
    public void onItemClick(@NonNull BaseQuickAdapter<?, ?> adapter, @NonNull View view, int position) {
        if (adapter == soundAdapter) {
            soundAdapter.getItem(soundPos).setSelected(false);
            soundPos = position;
            soundAdapter.getItem(position).setSelected(true);
            soundAdapter.notifyDataSetChanged();
            mAudioPlayer.pause();
            mDataBinding.ivImg.setImageResource(soundAdapter.getItem(position).getBigImg());
            mDataBinding.tvName.setText(soundAdapter.getItem(position).getName());
        } else if (adapter == durationAdapter) {
            durationAdapter.getItem(durationPos).setSelected(false);
            durationPos = position;
            durationAdapter.getItem(position).setSelected(true);
            durationAdapter.notifyDataSetChanged();
            duration = durationAdapter.getItem(position).getDuration();
        }
    }

    @Override
    protected void initData() {
        List<SoundBean> listData = new ArrayList<>();
        listData.add(new SoundBean(R.drawable.icon_dog, R.drawable.icon_dog2, "狗", R.raw.gou, false));
        listData.add(new SoundBean(R.drawable.icon_police, R.drawable.icon_police2, "警察", R.raw.jingcha, false));
        listData.add(new SoundBean(R.drawable.icon_cattle, R.drawable.icon_cattle2, "牛", R.raw.niu, false));
        listData.add(new SoundBean(R.drawable.icon_sheep, R.drawable.icon_sheep2, "羊", R.raw.yang, false));
        listData.add(new SoundBean(R.drawable.icon_frog, R.drawable.icon_frog2, "青蛙", R.raw.qingwa, false));
        listData.add(new SoundBean(R.drawable.icon_pig, R.drawable.icon_pig2, "猪", R.raw.zhu, false));
        listData.add(new SoundBean(R.drawable.icon_goast, R.drawable.icon_goast2, "鬼", R.raw.gui, false));
        listData.add(new SoundBean(R.drawable.icon_baby, R.drawable.icon_baby2, "婴儿", R.raw.yinger, false));
        listData.add(new SoundBean(R.drawable.icon_car, R.drawable.icon_car2, "卡车", R.raw.kache, false));
        listData.add(new SoundBean(R.drawable.icon_police_car, R.drawable.icon_police_car2, "警车", R.raw.jingche, false));
        listData.add(new SoundBean(R.drawable.icon_laba, R.drawable.icon_laba2, "喇叭", R.raw.laba, false));
        listData.add(new SoundBean(R.drawable.icon_lightning, R.drawable.icon_lightning2, "闪电", R.raw.shandian, false));
        listData.add(new SoundBean(R.drawable.icon_clock, R.drawable.icon_clock2, "闹钟", R.raw.naozhong, false));

        listData.get(soundPos).setSelected(true);
        mDataBinding.rvSoundList.smoothScrollToPosition(soundPos);
        mDataBinding.ivImg.setImageResource(listData.get(soundPos).getBigImg());
        mDataBinding.tvName.setText(listData.get(soundPos).getName());

        soundAdapter.setList(listData);

        settingBean = AppSpUtils.getSetting();
        duration = settingBean.getDuration();
        isFlashlight = settingBean.isFlashlight();
        isVibration = settingBean.isVibration();
        mDataBinding.ivFlashlightMode.setImageResource(isFlashlight ? R.drawable.akai : R.drawable.aguan);
        mDataBinding.ivVibrationMode.setImageResource(isVibration ? R.drawable.akai : R.drawable.aguan);

        List<DurationBean> listDuration = new ArrayList<>();
        String[] durationArr = getResources().getStringArray(R.array.duration_data);
        listDuration.add(new DurationBean(durationArr[0], 5 * 1000L, false));
        listDuration.add(new DurationBean(durationArr[1], 10 * 1000L, false));
        listDuration.add(new DurationBean(durationArr[2], 30 * 1000L, false));
        listDuration.add(new DurationBean(durationArr[3], 90 * 1000L, false));
        listDuration.add(new DurationBean(durationArr[4], 0, false));

        for (int i = 0; i < listDuration.size(); i++) {
            DurationBean durationBean = listDuration.get(i);
            if (settingBean.getDuration() == durationBean.getDuration()) {
                durationPos = i;
                listDuration.get(i).setSelected(true);
                break;
            }
        }
        durationAdapter.setList(listDuration);
    }

    private void apply() {
        settingBean.setRing(soundAdapter.getItem(soundPos).getRawId());
        settingBean.setDuration(duration);
        settingBean.setFlashlight(isFlashlight);
        settingBean.setVibration(isVibration);
        Log.e("TAG", "apply: " + duration);
        AppSpUtils.saveSetting(settingBean);
        ToastUtils.showShort(getString(R.string.apply_suc));
        startActivity(HomeActivity.class);
    }

    private void setVolume() {
        mDataBinding.tvProgress.setText(progress + getString(R.string.unit_percent));
        float value = calSeekBarRealValue(mDataBinding.sbProgress, progress);
        VolumeUtils.setVolume(AudioManager.STREAM_MUSIC, (int) value, 0);
    }

    private float calSeekBarRealValue(SeekBar seekBar, int progress) {
        int progressRange = seekBar.getMax();
        float value = progress * 1.0f / progressRange * (max - min) + min;
        return value;
    }

    @Override
    protected void onStop() {
        super.onStop();
        if (mAudioPlayer != null) {
            mAudioPlayer.pause();
        }
        mDataBinding.ivPlay.setImageResource(R.drawable.icon_play);
        mDataBinding.tvPlay.setText(getString(R.string.start_trial_listening));
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (mAudioPlayer != null) {
            mAudioPlayer.stop();
        }
    }

    private void showRingtoneChangeDialog(Integer original) {
        settingBean.setRing(soundAdapter.getItem(soundPos).getRawId());
        AppSpUtils.saveSetting(settingBean);
        RingtoneChangeDialog dialog = new RingtoneChangeDialog(mContext);
        dialog.setListener(new RingtoneChangeDialog.Ilistener() {
            @Override
            public void clickRevoke() {
                settingBean.setRing(original);
                AppSpUtils.saveSetting(settingBean);
            }
        });
        dialog.show();
    }

}